﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;

namespace BambolettaDB
{
    public class ManageCustomersVM: BaseVM
    {
        private ObservableCollection<CustomerVM> _Customers = new ObservableCollection<CustomerVM>();
        public ObservableCollection<CustomerVM> Customers
        {
            get { return _Customers; }
            set { _Customers = value; NotifyPropertyChanged("Customers"); }
        }

        private ObservableCollection<StringItemVM> _Status = new ObservableCollection<StringItemVM>();
        public ObservableCollection<StringItemVM> Status
        {
            get { return _Status; }
            set { _Status = value; NotifyPropertyChanged("Status"); }
        }

        private ObservableCollection<StringItemVM> _Locations = new ObservableCollection<StringItemVM>();
        public ObservableCollection<StringItemVM> Locations
        {
            get { return _Locations; }
            set { _Locations = value; NotifyPropertyChanged("Locations"); }
        }

        public ManageCustomersVM()
        {
            if (!App.IsInDesignMode)
            {
                Status = DBCommands.GetStatus();
                Customers = DBCommands.GetCustomers();
                Locations = DBCommands.GetLocations();
                Customers.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Customers_CollectionChanged);
            }
            else
            {
                CustomerVM cust = new CustomerVM();
                cust.Name = "Fake Name";
                cust.Email = "Fake Email";
                cust.Status = new StringItemVM(1, "Test", "Status", "Description");
            }
        }

        void Customers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (CustomerVM item in e.NewItems)
                {
                    DBCommands.InsertCustomer(item);
                }
            }

            if (e.OldItems != null)
            {
                foreach (CustomerVM item in e.OldItems)
                {
                    if (e.NewItems != null && e.NewItems.Contains(item))
                        DBCommands.UpdateCustomer(item);
                    else
                    {
                        if (MessageBox.Show("Delete this customer and all their requests?", "Delete Customer", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            DBCommands.DeleteRequestForCustomer(item);
                            DBCommands.DeleteCustomer(item);
                        }
                    }
                }
            }
        }
    }
}
